package com.we.web.servlet;

import com.we.entity.*;
import com.we.service.*;
import com.we.service.impl.*;
import com.we.util.JsonUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @ClassName NoteServlet
 * @Description 笔记请求处理
 * @Author cr7
 * @Date 2021-11-13 20:41
 * @Version V1.0
 */
@WebServlet("/note")
public class NoteServlet extends BaseServlet {

    private NoteService service = new NoteServiceImpl();
    private ResultInfo info = new ResultInfo();
    private TagService tagService = new TagServiceImpl();
    private CategoryService categoryService = new CategoryServiceImpl();
    private CommentService commentService = new CommentServiceImpl();
    private UserService userService=new UserServiceImpl();

    //查询所有笔记方法
    public void findAllNoteByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String currentPageStr = req.getParameter("currentPage");
        String pageSizeStr = req.getParameter("pageSize");

        int currentPage = 0;//当前页码，如果不传递，则默认为第一页
        if (currentPageStr != null && currentPageStr.length() > 0) {
            currentPage = Integer.parseInt(currentPageStr);
        } else {
            currentPage = 1;
        }

        int pageSize = 0;//每页显示条数，如果不传递，默认每页显示5条记录
        if (pageSizeStr != null && pageSizeStr.length() > 0) {
            pageSize = Integer.parseInt(pageSizeStr);
        } else {
            pageSize = 5;
        }

        PageBean<Note> pb = service.findAllNoteByPage(currentPage, pageSize);
        JsonUtils.writeValue(pb, resp);
    }

    //查询指定笔记方法(分页)
    public void findNoteBySearch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = req.getParameter("content");
        if (StringUtils.isBlank(content.trim())) {
            findAllNoteByPage(req, resp);
        } else {
            String currentPageStr = req.getParameter("currentPage");
            String pageSizeStr = req.getParameter("pageSize");

            int currentPage = 0;//当前页码，如果不传递，则默认为第一页
            if (currentPageStr != null && currentPageStr.length() > 0) {
                currentPage = Integer.parseInt(currentPageStr);
            } else {
                currentPage = 1;
            }

            int pageSize = 0;//每页显示条数，如果不传递，默认每页显示5条记录
            if (pageSizeStr != null && pageSizeStr.length() > 0) {
                pageSize = Integer.parseInt(pageSizeStr);
            } else {
                pageSize = 5;
            }

            PageBean<Note> pb = service.findAllNoteByPage(content, currentPage, pageSize);
            JsonUtils.writeValue(pb, resp);
        }
    }

    //发表笔记方法
    public void addNote(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            info.setFlag(false);
            info.setErrorMsg("当前用户未登录，请先登录");
            JsonUtils.writeValue(info, resp);
            return;
        }

        Note note = new Note();
        try {
            BeanUtils.populate(note, req.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        note.setAuthor(user.getUserName());

        int count = service.addNote(note);
        if (count > 0) {
            info.setFlag(true);
            user.setIsAuthor("Y");
        } else {
            info.setFlag(false);
            info.setErrorMsg("发布博客失败");
        }

        List<Note> noteList = service.findNoteByTime();

        int number = categoryService.saveCategory(req.getParameter("categoryName"), noteList.get(0).getNoteID());
        if (number <= 0) {
            info.setFlag(false);
            info.setErrorMsg("分类添加失败，请检查");
            JsonUtils.writeValue(info, resp);
            return;
        }

        String[] tagNames = req.getParameter("tagName").split(",");
        int length = 0;
        for (int i = 0; i < tagNames.length; i++) {
            length++;
            tagService.saveTag(tagNames[i], noteList.get(0).getNoteID());
        }
        if (length != tagNames.length) {
            info.setFlag(false);
            info.setErrorMsg("标签添加失败，请检查");
            JsonUtils.writeValue(info, resp);
            return;
        }

        JsonUtils.writeValue(info, resp);
    }

    //查询最新笔记
    public void findNoteByTime(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Note> noteList = service.findNoteByTime();
        if (noteList.isEmpty()) {
            info.setFlag(false);
            info.setErrorMsg("当前无最新笔记");
        } else {
            info.setFlag(true);
            info.setData(noteList);
        }
        JsonUtils.writeValue(info, resp);
    }

    //查询最热笔记方法
    public void findNoteByVisit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Note> noteList = service.findNoteByVisit();
        if (noteList.isEmpty()) {
            info.setFlag(false);
            info.setErrorMsg("当前无最热笔记");
        } else {
            info.setFlag(true);
            info.setData(noteList);
        }
        JsonUtils.writeValue(info, resp);
    }

    //查询笔记详情方法
    public void readNote(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String noteID = req.getParameter("noteID");
        if (StringUtils.isBlank(noteID)) {
            info.setFlag(false);
            info.setErrorMsg("查看博客失败");
            JsonUtils.writeValue(info, resp);
            return;
        }

        Note note = service.findNoteById(Integer.parseInt(noteID));
        User user=userService.findUserByName(note.getAuthor());
        List<Tag> tagList =tagService.findTagById(Integer.parseInt(noteID));
        List<Comment> commentList=commentService.findCommentById(Integer.parseInt(noteID));
        if (note == null) {
            info.setFlag(false);
            info.setErrorMsg("查看博客失败");
        } else {
            info.setFlag(true);
            info.setData(note);
            info.setDate1(tagList);
            info.setDate2(commentList);
            info.setDate3(user);
        }

        JsonUtils.writeValue(info, resp);
    }

    //查询分类下的笔记方法
    public void findNoteByCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String categoryName = req.getParameter("categoryName");
        if (StringUtils.isBlank(categoryName.trim())) {
            resp.getWriter().write("<script>alert(分类查询失败)</script>");
        } else {
            String currentPageStr = req.getParameter("currentPage");
            String pageSizeStr = req.getParameter("pageSize");

            int currentPage = 0;//当前页码，如果不传递，则默认为第一页
            if (currentPageStr != null && currentPageStr.length() > 0) {
                currentPage = Integer.parseInt(currentPageStr);
            } else {
                currentPage = 1;
            }

            int pageSize = 0;//每页显示条数，如果不传递，默认每页显示5条记录
            if (pageSizeStr != null && pageSizeStr.length() > 0) {
                pageSize = Integer.parseInt(pageSizeStr);
            } else {
                pageSize = 5;
            }

            PageBean<Note> pb = service.findNoteByCategory(categoryName, currentPage, pageSize);
            JsonUtils.writeValue(pb, resp);
        }
    }
}
